import type { ThemeConfig } from '@/types/theme';
import defaultSettings from '../../config/defaultSettings';
import { STATIC_PATHS } from '../../config/paths';

// 动态设置 input 聚焦时的 box-shadow 颜色
export function setInputBoxShadowColor(color: string) {
  // 支持 #RRGGBB 或 #RGB
  let hex = color.replace('#', '');
  if (hex.length === 3) {
    hex = hex
      .split('')
      .map((x) => x + x)
      .join('');
  }
  const bigint = parseInt(hex, 16);
  const r = (bigint >> 16) & 255;
  const g = (bigint >> 8) & 255;
  const b = bigint & 255;
  // 20% 透明度
  const shadow = `0 0 0 2px rgba(${r}, ${g}, ${b}, 0.2)`;
  document.documentElement.style.setProperty('--input-box-shadow', shadow);
}

// 保存主题配置到 localStorage
export const saveThemeConfig = (themeConfig: ThemeConfig) => {
  try {
    console.log('保存主题配置:', themeConfig);
    localStorage.setItem('themeConfig', JSON.stringify(themeConfig));

    // 更新页面标题
    if (themeConfig.layout?.title) {
      document.title = themeConfig.layout.title;
    }

    // 更新主色调 CSS 变量
    if (themeConfig.layout?.colorPrimary) {
      console.log('更新主色调 CSS 变量:', themeConfig.layout.colorPrimary);
      document.documentElement.style.setProperty(
        '--color-primary',
        themeConfig.layout.colorPrimary,
      );
      setInputBoxShadowColor(themeConfig.layout.colorPrimary);
    }

    // 更新菜单相关的 CSS 变量
    if (themeConfig.menu) {
      Object.entries(themeConfig.menu).forEach(([key, value]) => {
        if (value && typeof value === 'string') {
          console.log(`更新菜单 CSS 变量 --menu-${key}:`, value);
          document.documentElement.style.setProperty(`--menu-${key}`, value);
        }
      });
    }

    // 触发自定义事件通知主题变化
    console.log('触发主题变化事件');
    window.dispatchEvent(
      new CustomEvent('themeChange', {
        detail: themeConfig,
      }),
    );

    return true;
  } catch (error) {
    console.error('保存主题配置失败:', error);
    return false;
  }
};

// 从 localStorage 读取主题配置
export const loadThemeConfig = (): ThemeConfig | null => {
  try {
    const savedTheme = localStorage.getItem('themeConfig');
    if (savedTheme) {
      return JSON.parse(savedTheme);
    }
    return null;
  } catch (error) {
    console.error('读取主题配置失败:', error);
    return null;
  }
};

// 获取默认主题配置 - 基于 defaultSettings.ts
export const getDefaultThemeConfig = (): ThemeConfig => {
  return {
    footer: {
      copyright: '2024 Ant Design Pro',
    },
    welcome: {
      bg: STATIC_PATHS.images.bg,
    },
    login: {
      bg: STATIC_PATHS.images.bg,
    },
    user: {
      avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    },
    menu: {
      colorBgContainer: '#ffffff',
      colorText: '#000000d9',
      colorTextSecondary: '#00000073',
      colorPrimary: defaultSettings.colorPrimary || '#FA541C',
      colorBgElevated: '#ffffff',
      colorBorder: '#f0f0f0',
    },
    layout: {
      title: defaultSettings.title || 'Ant Design Pro',
      colorPrimary: defaultSettings.colorPrimary || '#FA541C',
      navTheme: defaultSettings.navTheme || 'light',
      layout: defaultSettings.layout || 'side',
      contentWidth: defaultSettings.contentWidth || 'Fluid',
      fixedHeader: defaultSettings.fixedHeader || false,
      fixSiderbar: defaultSettings.fixSiderbar || true,
      colorWeak: defaultSettings.colorWeak || false,
      splitMenus: defaultSettings.splitMenus || false,
      logo: defaultSettings.logo,
      token: defaultSettings.token,
    },
  };
};

// 预设主题配置
export const presetThemes = {
  default: {
    footer: {
      copyright: '2024 Ant Design Pro',
    },
    welcome: {
      bg: STATIC_PATHS.images.bg,
    },
    login: {
      bg: STATIC_PATHS.images.bg,
    },
    user: {
      avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    },
    menu: {
      colorBgContainer: '#1f1f1f',
      colorText: '#fff',
      colorTextSecondary: '#fff',
      colorPrimary: '#1890ff',
      colorBgElevated: '#1f1f1f',
      colorBorder: '#fff',
    },
    layout: {
      title: 'Ant Design Pro',
      colorPrimary: '#1890ff',
      navTheme: 'light' as const,
      layout: 'mix' as const,
      contentWidth: 'Fluid' as const,
      fixedHeader: false,
      fixSiderbar: true,
      colorWeak: false,
      splitMenus: false,
    },
  },
};

// 应用预设主题
export const applyPresetTheme = (themeName: keyof typeof presetThemes) => {
  const themeConfig = presetThemes[themeName];
  if (themeConfig) {
    console.log(`切换到主题: ${themeName}`, themeConfig);

    // 立即应用主题配置
    if (themeConfig.layout?.colorPrimary) {
      console.log(`设置主色调 CSS 变量: ${themeConfig.layout.colorPrimary}`);
      document.documentElement.style.setProperty(
        '--color-primary',
        themeConfig.layout.colorPrimary,
      );
      setInputBoxShadowColor(themeConfig.layout.colorPrimary);
    }

    // 应用菜单颜色配置
    if (themeConfig.menu) {
      Object.entries(themeConfig.menu).forEach(([key, value]) => {
        if (value && typeof value === 'string') {
          console.log(`设置菜单 CSS 变量 --menu-${key}: ${value}`);
          document.documentElement.style.setProperty(`--menu-${key}`, value);
        }
      });
    }

    const success = saveThemeConfig(themeConfig);
    if (success) {
      console.log('主题配置保存成功，主题已立即应用');
      // 不再重新加载页面，让主题立即生效
    }
    return success;
  }
  return false;
};
